'use client';

import { useState, useEffect } from 'react';
import ImportExportToolbar from './ImportExportToolbar';
import { downloadCsv, downloadXls, downloadXlsx, parseCsv, parseExcelXml, parseXlsx } from '@/lib/importExportUtils';

interface User {
  id: string;
  username: string;
  isAdmin: boolean;
  createdAt: string;
}

export default function UserManager() {
  const [users, setUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [showPasswordModal, setShowPasswordModal] = useState(false);
  const [newPassword, setNewPassword] = useState('');
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isImporting, setIsImporting] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const res = await fetch('/api/users');
      const data = await res.json();
      if (data.success) {
        setUsers(data.users);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const handleChangePassword = (user: User) => {
    setSelectedUser(user);
    setNewPassword('');
    setShowPasswordModal(true);
  };

  const handleSubmitPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedUser) return;

    try {
      const res = await fetch(`/api/users/${selectedUser.id}/password`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password: newPassword }),
      });
      const data = await res.json();
      if (data.success) {
        setShowPasswordModal(false);
        alert('密码修改成功');
      } else {
        alert(data.message);
      }
    } catch (error) {
      alert('修改密码失败');
    }
  };

  const paginatedUsers = users.slice((currentPage - 1) * pageSize, currentPage * pageSize);
  const totalPages = Math.ceil(users.length / pageSize);

  useEffect(() => {
    // 当数据变化时，重置到第一页
    setCurrentPage(1);
  }, [users]);

  const toggleSelectAll = (checked: boolean) => {
    if (checked) {
      const pageIds = new Set(paginatedUsers.filter(u => !u.isAdmin).map(u => u.id));
      setSelectedIds(prev => {
        const next = new Set(prev);
        pageIds.forEach(id => next.add(id));
        return next;
      });
    } else {
      const pageIds = new Set(paginatedUsers.filter(u => !u.isAdmin).map(u => u.id));
      setSelectedIds(prev => {
        const next = new Set(prev);
        pageIds.forEach(id => next.delete(id));
        return next;
      });
    }
  };

  const toggleSelectOne = (id: string, checked: boolean) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (checked) next.add(id); else next.delete(id);
      return next;
    });
  };

  const deleteOne = async (id: string) => {
    if (!confirm('确认删除该用户吗？此操作不可恢复。')) return;
    try {
      const res = await fetch(`/api/users?id=${encodeURIComponent(id)}`, { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        await fetchUsers();
        setSelectedIds(prev => { const n = new Set(prev); n.delete(id); return n; });
      } else {
        alert(data.message || '删除失败');
      }
    } catch {
      alert('删除失败');
    }
  };

  const deleteSelected = async () => {
    if (selectedIds.size === 0) return;
    if (!confirm(`确认删除选中的 ${selectedIds.size} 个用户吗？`)) return;
    try {
      const res = await fetch('/api/users', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ids: Array.from(selectedIds) }),
      });
      const data = await res.json();
      if (data.success) {
        await fetchUsers();
        setSelectedIds(new Set());
      } else {
        alert(data.message || '删除失败');
      }
    } catch {
      alert('删除失败');
    }
  };

  const handleExportSelected = (format: 'csv' | 'xls' | 'xlsx') => {
    const selected = users.filter(u => selectedIds.has(u.id));
    if (selected.length === 0) return;
    const headers = ['ID', '用户名', '角色', '注册时间'];
    const rows = selected.map(u => [u.id, u.username, u.isAdmin ? '管理员' : '普通用户', new Date(u.createdAt).toLocaleString('zh-CN')]);
    const filename = `users_selected_${Date.now()}`;
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows);
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows);
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows);
    }
  };

  const handleExportAll = (format: 'csv' | 'xls' | 'xlsx') => {
    if (users.length === 0) return;
    const headers = ['ID', '用户名', '角色', '注册时间'];
    const rows = users.map(u => [u.id, u.username, u.isAdmin ? '管理员' : '普通用户', new Date(u.createdAt).toLocaleString('zh-CN')]);
    const filename = `users_all_${Date.now()}`;
    if (format === 'csv') {
      downloadCsv(`${filename}.csv`, headers, rows);
    } else if (format === 'xls') {
      downloadXls(`${filename}.xls`, headers, rows);
    } else {
      downloadXlsx(`${filename}.xlsx`, headers, rows);
    }
  };

  const handleDownloadTemplate = (format: 'csv' | 'xls' | 'xlsx') => {
    const headers = ['用户名', '密码'];
    const example = ['demo_user', 'Passw0rd!'];
    if (format === 'csv') {
      downloadCsv('users_template.csv', headers, [example]);
    } else if (format === 'xls') {
      downloadXls('users_template.xls', headers, [example]);
    } else {
      downloadXlsx('users_template.xlsx', headers, [example]);
    }
  };

  const normalizeHeaderKey = (raw: string): string => {
    const trimmed = (raw || '').trim();
    const lower = trimmed.toLowerCase();
    // 支持中文和英文列名
    const map: Record<string, string> = {
      username: 'username', '用户名': 'username',
      password: 'password', '密码': 'password',
    };
    return map[trimmed] ?? map[lower] ?? lower;
  };

  const handleImport = async (file: File, format: 'csv' | 'xls' | 'xlsx') => {
    setIsImporting(true);
    try {
      let rows: string[][];
      if (format === 'csv') {
        const text = await file.text();
        rows = parseCsv(text);
      } else if (format === 'xls') {
        const text = await file.text();
        rows = parseExcelXml(text);
      } else {
        rows = await parseXlsx(file);
      }
      if (rows.length === 0) {
        alert(format === 'xls' ? 'Excel 为空或格式不受支持（请使用.xls XML工作簿或改用CSV）' : '文件为空');
        return;
      }
      const [h0, ...data] = rows;
      const header = h0.map(h => normalizeHeaderKey(String(h)));
      const idxUsername = header.indexOf('username');
      const idxPassword = header.indexOf('password');
      if (idxUsername < 0 || idxPassword < 0) {
        alert('缺少必要列：用户名(或username), 密码(或password)');
        return;
      }
      let ok = 0, failed = 0;
      const errors: string[] = [];
      for (let i = 0; i < data.length; i++) {
        const r = data[i];
        const username = String(r[idxUsername] || '').trim();
        const password = String(r[idxPassword] || '').trim();
        if (!username || !password) {
          failed++;
          errors.push(`第${i + 2}行：用户名和密码不能为空`);
          continue;
        }
        try {
          const res = await fetch('/api/auth/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password })
          });
          const dataJson = await res.json();
          if (dataJson.success) {
            ok++;
          } else {
            failed++;
            errors.push(`第${i + 2}行：${dataJson.message || '创建失败'}`);
          }
        } catch {
          failed++;
          errors.push(`第${i + 2}行：网络错误`);
        }
      }
      await fetchUsers();
      alert(`导入完成：成功 ${ok} 条，失败 ${failed} 条${errors.length > 0 ? '\n\n前5个错误：\n' + errors.slice(0, 5).join('\n') : ''}`);
    } catch (e) {
      if (e instanceof Error && e.message.includes('xlsx')) {
        alert('请先安装 xlsx 库: npm install xlsx');
      } else {
        alert(`导入失败：${e instanceof Error ? e.message : '未知错误'}`);
      }
    } finally {
      setIsImporting(false);
    }
  };

  return (
    <div>
      <h2 style={{ marginBottom: '20px' }}>用户管理</h2>

      <div className="card">
        <div style={{ display: 'flex', gap: '10px', marginBottom: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
          <button className="btn btn-secondary" onClick={deleteSelected} disabled={selectedIds.size === 0}>删除选中</button>
          <ImportExportToolbar
            onExportSelected={handleExportSelected}
            onExportAll={handleExportAll}
            onImport={handleImport}
            onDownloadTemplate={handleDownloadTemplate}
            isImporting={isImporting}
            selectedCount={selectedIds.size}
            totalCount={users.length}
          />
        </div>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ backgroundColor: '#f5f5f5' }}>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>
                  <input type="checkbox" checked={paginatedUsers.filter(u => !u.isAdmin).length > 0 && paginatedUsers.filter(u => !u.isAdmin).every(u => selectedIds.has(u.id))} onChange={e => toggleSelectAll(e.target.checked)} />
                </th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>用户名</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>角色</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>注册时间</th>
                <th style={{ padding: '10px', textAlign: 'left', borderBottom: '2px solid #ddd' }}>操作</th>
              </tr>
            </thead>
            <tbody>
              {paginatedUsers.map(user => (
                <tr key={user.id} style={{ borderBottom: '1px solid #eee' }}>
                  <td style={{ padding: '10px' }}>
                    <input type="checkbox" disabled={user.isAdmin} checked={!user.isAdmin && selectedIds.has(user.id)} onChange={e => !user.isAdmin && toggleSelectOne(user.id, e.target.checked)} />
                  </td>
                  <td style={{ padding: '10px' }}>{user.username}</td>
                  <td style={{ padding: '10px' }}>
                    {user.isAdmin ? (
                      <span style={{ color: '#0070f3', fontWeight: 'bold' }}>管理员</span>
                    ) : (
                      <span>普通用户</span>
                    )}
                  </td>
                  <td style={{ padding: '10px' }}>
                    {new Date(user.createdAt).toLocaleString('zh-CN')}
                  </td>
                  <td style={{ padding: '10px' }}>
                    <button
                      className="btn btn-secondary"
                      style={{ padding: '5px 10px', fontSize: '14px' }}
                      onClick={() => handleChangePassword(user)}
                    >
                      修改密码
                    </button>
                    {!user.isAdmin && (
                      <button className="btn btn-danger" style={{ padding: '5px 10px', fontSize: '14px', marginLeft: 8 }} onClick={() => deleteOne(user.id)}>删除</button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {users.length === 0 && <p style={{ padding: '20px', textAlign: 'center' }}>暂无用户</p>}
          {users.length > 0 && (
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '15px', borderTop: '1px solid #eee' }}>
              <div>
                共 {users.length} 条，第 {currentPage} / {totalPages} 页
              </div>
              <div style={{ display: 'flex', gap: '8px' }}>
                <button className="btn" onClick={() => setCurrentPage(1)} disabled={currentPage === 1}>首页</button>
                <button className="btn" onClick={() => setCurrentPage(p => Math.max(1, p - 1))} disabled={currentPage === 1}>上一页</button>
                <button className="btn" onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))} disabled={currentPage === totalPages}>下一页</button>
                <button className="btn" onClick={() => setCurrentPage(totalPages)} disabled={currentPage === totalPages}>末页</button>
              </div>
            </div>
          )}
        </div>
      </div>

      {showPasswordModal && selectedUser && (
        <div className="modal" onClick={() => setShowPasswordModal(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <h2>修改密码 - {selectedUser.username}</h2>
            <form onSubmit={handleSubmitPassword}>
              <div style={{ marginBottom: '15px' }}>
                <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
                  新密码
                </label>
                <input
                  type="password"
                  className="input"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  required
                  minLength={6}
                />
              </div>
              <div style={{ display: 'flex', gap: '10px' }}>
                <button type="submit" className="btn btn-primary">
                  确认修改
                </button>
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => setShowPasswordModal(false)}
                >
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {isImporting && (
        <div
          style={{
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(255, 255, 255, 0.7)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            zIndex: 2000,
            pointerEvents: 'auto',
            cursor: 'wait',
          }}
        >
          <div style={{ padding: '24px 32px', backgroundColor: '#fff', borderRadius: '8px', boxShadow: '0 4px 12px rgba(0,0,0,0.15)', fontSize: '16px', color: '#333' }}>
            正在导入文件，请稍候...
          </div>
        </div>
      )}
    </div>
  );
}

